package pidlock;

use Fcntl ':flock'; 
use strict;

my $errormsg="";

sub error {
	return $errormsg;
}

sub new {
my $self={};
my $class=shift;

	$errormsg=undef;
	if(!defined($_[0])) {
		$errormsg="Missing daemon name.";
		return undef;
	}
	$self->{DAEMON}=$_[0];
	bless($self,$class);
	return $self;
}

sub getlock {
my $self=shift;
my $fd;
my $pid=$$;

	$errormsg=undef;
	if(!open($fd,">>/var/run/lha2_$self->{DAEMON}.pid")) {
		$errormsg="Unable to open '/var/run/lha2_$self->{DAEMON}.pid' for writing: $!";
		return 0;
	}
	if(!flock($fd,LOCK_EX|LOCK_NB)) {
		$errormsg="Failed to obtain lock - already locked!";
		return 0;
	}
	seek($fd,0,0);
	if(!print $fd "$pid\n") {
		$errormsg="Failed to write PID to lock file: $!";
		return 0;
	}
	$self->{FD}=$fd;
	return 1;
}

sub islocked() {
my $self=shift;
my $fd;

	$errormsg=undef;
	if(! -f "/var/run/lha2_$self->{DAEMON}.pid") {
		return 0;
	}
	if(!open($fd,">>/var/run/lha2_$self->{DAEMON}.pid")) {
		$errormsg="Unable to open '/var/run/lha2_$self->{DAEMON}.pid' for writing: $!";
		return -1;
	}
	if(!flock($fd,LOCK_EX|LOCK_NB)) {
		close($fd);
		return 1;
	}
	close($fd);
	return 0;
}

sub releaselock {
my $self=shift;

	$errormsg=undef;
	return if !exists($self->{FD});
	unlink "/var/run/lha2_$self->{DAEMON}.pid";
	close($self->{FD});
	delete $self->{FD};
}

1;


